package com.example.skincoredemo;

import android.app.Application;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.text.TextUtils;
import android.view.LayoutInflater;

import com.example.skincoredemo.utils.SkinPreference;
import com.example.skincoredemo.utils.SkinResources;

import java.lang.reflect.Method;
import java.util.Observable;

/**
 *  通过AssetManager替换来实现换肤。
 */
public class SkinManager extends Observable {

    private volatile static SkinManager instance;

    private Application application;

    private SkinManager(Application application){
        this.application = application;
        SkinPreference.init(application);
        SkinResources.init(application);
        application.registerActivityLifecycleCallbacks(new SkinActivityLifecycle());

        loadSkin(SkinPreference.getInstance().getSkin());
    }

    public static SkinManager getInstance() {
        return instance;
    }

    public void loadSkin(String path) {
        if (TextUtils.isEmpty(path)) {
            // 重置为默认皮肤
            SkinPreference.getInstance().setSkin("");
            // 清空资源管理、皮肤资源属性
            SkinResources.getInstance().reset();
        } else {
            // 通过反射创建AssetManager
            try {
                AssetManager manager = AssetManager.class.newInstance();
                // 资源路径设置：目录或者压缩包
                Method addAssetPath = manager.getClass().getMethod("addAssetPath", String.class);
                addAssetPath.invoke(manager, path);

                Resources appResources= this.application.getResources();
                Resources skinResources = new Resources(manager, appResources.getDisplayMetrics(), appResources.getConfiguration());

                // 将皮肤包的路径保存
                SkinPreference.getInstance().setSkin(path);

                // 获取外部apk（皮肤包）的包名
                PackageManager packageManager = this.application.getPackageManager();
                PackageInfo packageArchiveInfo = packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
                String packageName = packageArchiveInfo.packageName;

                SkinResources.getInstance().applySkin(skinResources,packageName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 采集的View 皮肤包加载完成，通知外部观察者
        setChanged();
        notifyObservers();
    }

    public static void init(Application application) {
        synchronized (SkinManager.class) {
            if (instance == null) {
                instance = new SkinManager(application);
            }
        }
    }
}
